<template>
  <el-button 
    :type="type" 
    :size="size" 
    :icon="Download" 
    :disabled="disabled"
    @click="handleDownload"
    :class="customClass"
  >
    {{ text || '下载' }}
  </el-button>
</template>

<script setup>
import { Download } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { defineProps, defineEmits } from 'vue';
import axios from 'axios';

const props = defineProps({
  // 下载的文档ID
  documentId: {
    type: String,
    default: ''
  },
  // 下载的文件名
  fileName: {
    type: String,
    default: '文档'
  },
  // 按钮文本
  text: {
    type: String,
    default: '下载文档'
  },
  // 按钮类型
  type: {
    type: String,
    default: 'primary'
  },
  // 按钮大小
  size: {
    type: String,
    default: 'small'
  },
  // 按钮是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 自定义样式类
  customClass: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['download-success', 'download-error']);

// 处理下载操作
const handleDownload = async () => {
  try {
    // 检查是否有文档ID
    if (!props.documentId) {
      ElMessage.warning('没有指定要下载的文档');
      emit('download-error', '没有指定要下载的文档');
      return;
    }

    // 获取文档下载链接
    const downloadUrl = `/adminapi/documentation/download/${props.documentId}`;

    // 使用axios直接下载文件，支持文件流 
    const response = await axios.get(downloadUrl, {
      responseType: 'blob' // 重要：设置响应类型为blob
    });
    
    // 从Content-Disposition头解析文件名
    let filename = props.fileName + '.md';
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename="(.+)"/);
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1]);
      }
    }
    
    // 创建Blob对象和下载链接
    const blob = new Blob([response.data], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    
    const downloadLink = document.createElement('a');
    downloadLink.href = url;
    downloadLink.download = filename;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    
    // 清理
    document.body.removeChild(downloadLink);
    URL.revokeObjectURL(url);
    
    ElMessage.success("文档下载成功");
    emit('download-success', response.data);
  } catch (error) {
    console.error("下载失败:", error);
    ElMessage.error("文档下载失败");
    emit('download-error', error);
  }
};
</script>

<style scoped>
.el-button {
  margin: 0 5px;
}
</style>
